/*
 * @Author: 涵崽
 * @Date: 2023-11-13 14:43:16
 * @email: 1045654@qq.com
 * @gitee: https://gitee.com/han-zai
 * @LastEditors: 涵崽
 * @LastEditTime: 2023-12-05 15:27:50
 * @Description: 微信：1045654
 */
// 导出一个对象，该对象拥有get与post方法用于发送相应类型的请求
import qs from "qs";
import axios from "axios";
import { getToken, removeToken } from "@/utils/auth"; 
import { Message } from "element-ui";
const instance = axios.create();

// 请求拦截器
instance.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers["token"] = getToken();
    }
    return config;
  },
  error => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    // 拦截成功响应
    const { data } = response;
    if (data.code === 401) {
      removeToken();
      Message({
        message: data.msg,
        type: "info",
        duration: 5 * 1000,
      });
      location.href = "/";
    } else if (data.code == 2001) {
      Message({
        message: data.msg,
        type: "warning",
        duration: 5 * 1000,
      });
    }
    return response;
  },
  error => {
    // 拦截错误响应
    return Promise.reject(error);
  }
);
const myaxios = {
  /**
   * 用于发送 get 请求
   * @param {string} url 请求路径
   * @param {object} params 请求参数对象  {参数名:参数值}
   */
  get(url, params) {
    return instance({
      url,
      method: "GET",
      params,
    });
  },

  /**
   * 用于发送 post 请求
   * @param {string} url 请求路径
   * @param {object} data 请求参数对象  {参数名:参数值}
   */
  post(url, data, responseType = "json") {
    return instance({
      url,
      method: "POST",
      responseType: responseType,
      data: qs.stringify(data),
    });
  },
};

export default myaxios;
